package middleware

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"poem-server/comm/response"
	"poem-server/initialize/config"
	"poem-server/mvc/service"
	"strings"
)

func JWTAuth(GuardName string) gin.HandlerFunc {
	return func(context *gin.Context) {
		tokenStr := context.Request.Header.Get("Authorization")
		if tokenStr == "" {
			response.TokenFail(context)
			context.Abort()
			return
		}
		tokenStr = tokenStr[len(service.TokenType)+1:] // 取出bearer 之后的字符串

		// token 解析校验
		token, err := jwt.ParseWithClaims(tokenStr, &service.CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
			return []byte(config.Config.Jwt.Secret), nil
		})
		// 黑名单校验
		if err != nil || service.JwtService.IsBlacklist(tokenStr) {
			response.TokenFail(context)
			context.Abort()
			return
		}

		// Token发布者校验
		claims := token.Claims.(*service.CustomClaims)
		if claims.Issuer != GuardName {
			response.TokenFail(context)
			context.Abort()
			return
		}
		context.Set("token", token)
		context.Set("id", claims.Id)
	}
}

// 获取token
func getAuthorization(ctx *gin.Context) string {
	token := ctx.GetHeader("Authorization")
	if len(token) == 0 || strings.ToLower(token) == "null" {
		token = ctx.Query("Authorization")
		if len(token) == 0 || strings.ToLower(token) == "null" {
			return ""
		}
	}
	if strings.HasPrefix(token, "bearer") {
		token = strings.TrimSpace(strings.Replace(token, "bearer", "", 1))
	}
	if strings.HasPrefix(token, "Bearer") {
		token = strings.TrimSpace(strings.Replace(token, "Bearer", "", 1))
	}
	return token

}
